package com.yakami.ocean.view.activity;

import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jakewharton.rxbinding.view.RxView;
import com.yakami.ocean.AppManager;
import com.yakami.ocean.R;
import com.yakami.ocean.ServerAPI;
import com.yakami.ocean.bean.News;
import com.yakami.ocean.listener.ScrollerBottomLayoutDelegation;
import com.yakami.ocean.utils.Tools;
import com.yakami.ocean.view.activity.base.BaseHoldBackActivity;

import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author Yakami, Created on 2016/4/10
 */
public class DetailActivity extends BaseHoldBackActivity {

    @Bind(R.id.loading) RelativeLayout mLoadingLayout;
    @Bind(R.id.load_error) TextView mLoadErrorLayout;
    @Bind(R.id.invalid_data) TextView mInvalidTextLayout;
    @Bind(R.id.view_content) NestedScrollView mContentLayout;
    @Bind(R.id.layout_web_view) WebView mWebView;
    @Bind(R.id.title) TextView mArticleTitle;
    @Bind(R.id.bottom_bar) ViewGroup mBottomLayout;
    @Bind(R.id.thumb_up_icon) LinearLayout mThumbLayout;
    @Bind(R.id.thumb_img) ImageView mThumbImg;
    @Bind(R.id.thumb_text) TextView mThumbText;
    @Bind(R.id.collection_icon) LinearLayout mCollectionLayout;
    @Bind(R.id.collection_img) ImageView mCollectionImg;
    @Bind(R.id.collection_text) TextView mCollectionText;

    public static final int LOADING = 1;
    public static final int ERROR = 2;
    public static final int SUCCESS = 3;
    public static final int PARSE_ERROR = 4;

    private News mNews;
    private Rect mScrollBounds = new Rect();
    private boolean mIsChanged = false;

    private boolean mHasCollected;
    private boolean mHasThumbed;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mTitle.setText(mRes.getString(R.string.detail));

        mNews = (News) getIntentHelper().getSerializable("data");
        if (mNews == null) {
            switchState(PARSE_ERROR);
            return;
        }
        requestData(mNews.articleId);
        RxView.clicks(mLoadErrorLayout)
                .throttleFirst(500, TimeUnit.MICROSECONDS)
                .subscribe(Void -> {
                    requestData(mNews.articleId);
                });

        //根据滑动，自动改变标题
        mContentLayout.getHitRect(mScrollBounds);
        mContentLayout.setOnScrollChangeListener((NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) -> {
                    if (scrollY == 0) {
                        mTitle.setText(mRes.getString(R.string.detail));
                        mIsChanged = false;
                    } else if (!mIsChanged) {
                        mTitle.setText(mArticleTitle.getText());
                        mIsChanged = true;
                    }
                }
        );

        initBottomBar();

        //委托底栏自动隐藏、显示
        ScrollerBottomLayoutDelegation.delegation(mContentLayout, mBottomLayout);
    }

    private void initBottomBar() {
        //检查是否已收藏
        if (AppManager.mUser != null) {
            ServerAPI.getOceanAPI()
                    .isCollected(mNews.articleId)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(result -> {
                        if (result.isResult()) {
                            toggleCollectionIcon(true);
                        }
                    }, Throwable::printStackTrace);
        }

        RxView.clicks(mThumbLayout)
                .throttleFirst(500, TimeUnit.MICROSECONDS)
                .subscribe(Void -> {
                    if (mHasThumbed) {
                        Tools.toast(AppManager.context, mRes.getString(R.string.has_thumb));
                        return;
                    }
                    ServerAPI.getOceanAPI()
                            .thumbUp(mNews.articleId)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(result -> {
                                if (result.isResult())
                                    toggleThumbIcon(true);
                            }, Throwable::printStackTrace);
                });

        RxView.clicks(mCollectionLayout)
                .throttleFirst(500, TimeUnit.MICROSECONDS)
                .subscribe(Void -> {
                    if (mHasCollected) {
                        ServerAPI.getOceanAPI()
                                .cancelCollection(mNews.articleId)
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(result -> {
                                    if (result.result.equals("ok!")) {
                                        toggleCollectionIcon(false);
                                        Tools.toast(AppManager.context, mRes.getString(R.string.has_cancel_collection));
                                    }
                                }, Throwable::printStackTrace);
                        return;
                    }
                    if (AppManager.mUser == null) {
                        Tools.toast(AppManager.context, mRes.getString(R.string.please_login_first));
                        return;
                    }
                    ServerAPI.getOceanAPI()
                            .collectArticle(mNews.articleId)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(result -> {
                                if (result.result.equals("ok!")) {
                                    toggleCollectionIcon(true);
                                }
                            }, Throwable::printStackTrace);
                });
    }

    private void toggleCollectionIcon(boolean open) {
        if (open) {
            mCollectionImg.setColorFilter(mRes.getColor(R.color.PeterRiver));
            mCollectionText.setTextColor(mRes.getColor(R.color.PeterRiver));
            mCollectionText.setText(mRes.getString(R.string.has_collection));
            mHasCollected = true;
        } else {
            mCollectionImg.clearColorFilter();
            mCollectionText.setTextColor(mRes.getColor(R.color.icon_grey));
            mCollectionText.setText(mRes.getString(R.string.collection));
            mHasCollected = false;
        }
    }

    private void toggleThumbIcon(boolean open) {
        if (open) {
            mThumbImg.setColorFilter(mRes.getColor(R.color.PeterRiver));
            mThumbText.setTextColor(mRes.getColor(R.color.PeterRiver));
            mThumbText.setText(mRes.getString(R.string.has_thumb));
            mHasThumbed = true;
        } else {
            mThumbImg.clearColorFilter();
            mThumbText.setTextColor(mRes.getColor(R.color.icon_grey));
            mThumbText.setText(mRes.getString(R.string.thumb_up));
            mHasThumbed = false;
        }
    }

    private void requestData(int id) {
        switchState(LOADING);
        ServerAPI.getOceanAPI()
                .getRawArticle(id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe((body) -> {
                    try {
                        switchState(SUCCESS);
                        mWebView.resumeTimers();
                        mWebView.loadUrl("about:blank");
                        String html = body.string();
                        mArticleTitle.setText(mNews.title);
                        StringBuilder result = new StringBuilder();
                        result.append("<body class=\"article-content>\"");
                        result.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"file:///android_asset/bootstrap.min.css\">\n" +
                                "<link rel=\"stylesheet\" type=\"text/css\" href=\"file:///android_asset/article.css\">\n" +
                                "<link rel=\"stylesheet\" type=\"text/css\" href=\"file:///android_asset/video-js.min.css\">\n" +
                                "<script src=\"file:///android_asset/jquery-1.10.2.min.js\"></script>\n" +
                                "<script src=\"file:///android_asset/bootstrap.min.js\"></script>\n");
                        html = html.replace("type=\"video/x-flv\"", "type=\"video/mp4\"");// <source src="http://112.74.204.89/Uploads/
                        html = html.replace("<img src=\"/Uploads/", "<img src=\"" + ServerAPI.host + "/Uploads/");

                        result.append(html);
                        result.append("</body>");
                        mWebView.setWebChromeClient(new WebChromeClient() {
                        });
                        mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
                        mWebView.getSettings().setJavaScriptEnabled(true);
//                        mWebView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
                        mWebView.loadDataWithBaseURL(null, result.toString(), "text/html", "UTF-8", null);
//                        mWebView.setVisibility(View.VISIBLE);
                    } catch (Exception e) {
                        e.printStackTrace();
                        switchState(PARSE_ERROR);
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    switchState(ERROR);
                });

    }

    @Override
    public void onStop() {
//        mWebView.stopLoading();

//        if(mWebView != null) {
//            mWebView.clearHistory();

//            mWebView = null;
//        }
        super.onStop();
    }

    @Override
    public void onDestroy() {
        mWebView.stopLoading();
        mWebView.loadUrl("about:blank");
        mWebView.destroy();
        mWebView = null;
        mContentLayout.removeAllViews();
        super.onDestroy();
        System.gc();
    }

    private void switchState(int state) {
        mLoadingLayout.setVisibility(state == LOADING ? View.VISIBLE : View.GONE);
        mLoadErrorLayout.setVisibility(state == ERROR ? View.VISIBLE : View.GONE);
        mContentLayout.setVisibility(state == SUCCESS ? View.VISIBLE : View.GONE);
        mInvalidTextLayout.setVisibility(state == PARSE_ERROR ? View.VISIBLE : View.GONE);
    }

    @Override
    protected int onBindLayout() {
        return R.layout.activity_detail;
    }
}
